import ProductAPI from '@/api/Product';
import ProductInfoAPI from '@/api/ProductInfo';
import { Box, FieldCols, mapField, useCall, useFormValue, useQueryValues, useReq } from '@/components';
import { MAIN_RISK_TYPE } from '@/constants/options';
import { getAccept } from '@/utils';
import { Button, Form, message, Space } from 'antd';
import React, { useEffect, useRef } from 'react';
import InfoGroupEdit from './components/InfoGroupEdit';
import { dataToForm, formToData } from './components/shared';

function AttachmentEditPage(props) {
  const [relationCode, productId, productType] = useQueryValues('businessCode', 'id', 'productType');
  const infoSaveXhr = useReq(ProductInfoAPI.insertOrUpdate);
  const termSaveXhr = useReq(ProductAPI.updateClause);
  const updateStatusXhr = useReq(ProductAPI.updateInfoStatus);
  const cacheRef = useRef({});
  const composeXhr = useReq((relationCode, options) =>
    Promise.all([
      /**/
      ProductInfoAPI.view({ relationCode }, options),
      ProductAPI.getClause(relationCode, options),
    ]),
  );

  const loading = [
    //
    composeXhr.status,
    infoSaveXhr.status,
    termSaveXhr.status,
    updateStatusXhr.status,
  ].includes('loading');

  const isMainRisk = productType === MAIN_RISK_TYPE;

  const [form] = Form.useForm();

  useEffect(() => {
    if (relationCode) {
      composeXhr.start(relationCode);
    }
  }, [relationCode]);

  useEffect(() => {
    if (composeXhr.result) {
      const [{ data: productInfo }, { data: productTerms }] = composeXhr.result;
      cacheRef.current = { productInfo, productTerms };
      const formData = dataToForm(productInfo, productTerms);
      form.setFieldsValue(formData);
    }
  }, [composeXhr.result]);

  const accept = getAccept('image', 'pdf');
  const merge = {
    noStyle: true,
    uploadProps: { multiple: true, accept: getAccept('image', 'doc', 'video') },
  };

  // 产品条款
  const terms = [
    '_terms',
    null,
    InfoGroupEdit,
    {
      titleReadOnly: true,
      defaultTitle: '产品条款',
      disableRichText: true,
      uploadProps: { accept: '.pdf', hideName: true },
      disabled: isMainRisk,
      text: '*主险的产品条款请到"停/在售管理"页面进行配置',
    },
  ];

  // 运营服务
  const files = [
    '_files',
    null,
    InfoGroupEdit,
    {
      titleReadOnly: true,
      defaultTitle: '运营服务',
      disableRichText: true,
      renderFields: [
        ['SF', '投保流程', 'named-upload', { accept, fileNameProp: 'SF_name', fileTypeProp: 'SF_type' }],
        ['PP', '保全流程', 'named-upload', { accept, fileNameProp: 'PP_name', fileTypeProp: 'PP_type' }],
        ['CF', '理赔流程', 'named-upload', { accept, fileNameProp: 'CF_name', fileTypeProp: 'CF_type' }],
      ].map(mapField),
    },
  ];

  const getInfoLib = (name, label, accepts = ['all'], rest = null) => [
    name,
    null,
    InfoGroupEdit,
    {
      titleReadOnly: true,
      disableRichText: true,
      ...rest,
      defaultTitle: label,
      getColProps(e, i, form) {
        const size = useFormValue(form, name, (v) => v?.list?.length);
        return { hidden: rest?.disabled && !size };
      },
      uploadProps: { accept: getAccept(...accepts), ...rest?.uploadProps },
    },
  ];

  const infoLib = (productType === MAIN_RISK_TYPE
    ? [
        getInfoLib('PI', '产品介绍', ['all'], { disabled: true, uploadProps: { multiple: true } }),
        terms, // 条款
        files, // 运营服务
        getInfoLib('HN', '健康告知', ['all'], { disabled: true, uploadProps: { multiple: true } }),
        getInfoLib('PN', '投保须知', ['all'], { disabled: true, uploadProps: { multiple: true } }),
        getInfoLib('FT', '费率表', ['all'], { disabled: true, uploadProps: { multiple: true } }),
        getInfoLib('QP', '职业类别表', ['doc'], { uploadProps: { multiple: false, accept: getAccept('doc') } }),
        getInfoLib('BS', '支持银行', ['all'], { disabled: true, uploadProps: { multiple: true } }),
        getInfoLib('AS', '附加服务', ['all'], { disabled: true, uploadProps: { multiple: true } }),
        getInfoLib('SP', '常见问题', ['all'], { disabled: true, uploadProps: { multiple: true } }),
      ]
    : [
        // 附加险配置
        terms,
      ]
  ).map(mapField, { merge });

  const infoLibTab = (
    <FieldCols form={form} fields={infoLib} colProps={{ xs: 24, md: 24, xl: 24 }} wrapperSpan={24} labelSpan={0} />
  );

  const onSave = useCall(async () => {
    const formData = form.getFieldsValue();

    const { infoList, removeInfoList, termsList, removeTermsList } = formToData(
      relationCode,
      formData,
      cacheRef.current?.productInfo,
      cacheRef.current?.productTerms,
    );

    // const uploadedTypes = arrayUnique(infoList.map((v) => v.showContentType));
    // const attachmentStatus = ['PC', 'PE'].every((k) => uploadedTypes.includes(k)) &&
    // termsList.length ? '1' : '0'; // 上传状态检查
    console.log(formData, { infoList, removeInfoList, termsList, removeTermsList });

    if (removeInfoList.length > 0) ProductInfoAPI.deleteItems(removeInfoList).catch(console.error);
    if (removeTermsList.length > 0) ProductAPI.deleteClause(removeTermsList.map((v) => v.id)).catch(console.error);

    await Promise.all([
      infoList.length && infoSaveXhr.start(infoList),
      termsList.length && termSaveXhr.start(termsList),
      // updateStatusXhr.start(productId, attachmentStatus),
    ]);
    message.success('保存成功');

    props.history?.goBack();
  });

  return (
    <>
      <Form component={false} form={form}>
        {/*<Tabs>
          <Tabs.TabPane key='1' tab='产品详情' forceRender>
            {prodDetailTab}
          </Tabs.TabPane>

          <Tabs.TabPane key='2' tab='资料库' forceRender>
            {infoLibTab}
          </Tabs.TabPane>
        </Tabs>*/}
        {infoLibTab}

        <Box flex jus='center' py={3} className='form-page-btn'>
          <Space size='large'>
            <Button onClick={props.history?.goBack}>返回</Button>
            <Button type='primary' onClick={onSave}>
              保存
            </Button>
          </Space>
        </Box>
      </Form>
    </>
  );
}

export default AttachmentEditPage;
